//
//  NSString+url.m
//  funlive
//
//  Created by rckj on 16/5/30.
//  Copyright © 2016年 renzhen. All rights reserved.
//

#import "NSString+url.h"

@implementation NSString (url)

-(NSString*)getUrlWithoutParamters
{
    if ( [self containsString:@"?"] ) {
        return [self substringToIndex:[self rangeOfString:@"?"].location];
    }
    return self;
}

- (NSString *)parametersString{
    NSRange range = [self rangeOfString:@"?"];
    if (range.location == NSNotFound){
        return self;
    }
    return [self substringFromIndex:range.location + range.length];
}
- (NSString *)URLEncodeParamters{
    
    NSRange range = [self rangeOfString:@"?"];
    if (range.location == NSNotFound){
        return self;
    }
    NSString *domain = [self substringToIndex:range.location];
    
    NSString *paramters = [self substringFromIndex:range.location + range.length];
    
    return [domain stringByAppendingFormat:@"?%@", [paramters URLEncodedString]];
}

//- (NSArray *)keyValues{
//    NSError *error;
//    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+([^&]*)(&|$)=+([^&]*)(&|$)"];
//    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
//                                                                           options:NSRegularExpressionCaseInsensitive
//                                                                             error:&error];
//    
//    return [regex matchesInString:self
//                          options:0
//                            range:NSMakeRange(0, [self length])];
//}

-(NSString *)valueForKey:(NSString *)key
{
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", key];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    NSArray *matches = [regex matchesInString:self
                                      options:0
                                        range:NSMakeRange(0, [self length])];
    
    for (NSTextCheckingResult *match in matches)
    {
        NSString *tagValue = [self substringWithRange:[match rangeAtIndex:2]];
        return tagValue;
    }
    return @"";
}
- (NSArray <NSValue *>*)rangeAllOfString:(NSString *)string{
    NSMutableArray <NSValue *> *rangeArray = [NSMutableArray new];
    NSRange range = [self rangeOfString:string];
    while (range.location != NSNotFound) {
        [rangeArray addObject:[NSValue valueWithRange:range]];
        NSRange nextRange = NSMakeRange(range.length+range.location, self.length-range.location-range.length);
        range = [self rangeOfString:string options:NSForcedOrderingSearch range:nextRange];
    }
    
    return rangeArray;
}
- (NSString*)excludeKeys:(NSArray*)keys{
    __block NSString *excludeURL = self;
    
    for (id key in keys){
        NSError *error;
        NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", key];
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&error];
        
        NSArray *matches = [regex matchesInString:excludeURL
                                          options:0
                                            range:NSMakeRange(0, [excludeURL length])];
        
        for (NSTextCheckingResult *match in matches){
            NSString *subStr = [excludeURL substringWithRange:match.range];
            
            NSArray *ranges = [subStr rangeAllOfString:@"&"];
            
            if (ranges.count > 0){
                if(ranges.count > 1){
                    excludeURL = [excludeURL stringByReplacingCharactersInRange:match.range withString:@"&"];
                }else{
                    ranges = [subStr rangeAllOfString:@"?"];
                    if(ranges.count > 0){
                        NSRange range = [[ranges firstObject] rangeValue];
                        if(range.location == 0){
                            excludeURL = [excludeURL stringByReplacingCharactersInRange:match.range withString:@"?"];
                        }else{
                            excludeURL = [excludeURL stringByReplacingCharactersInRange:match.range withString:@""];
                        }
                    }else{
                        excludeURL = [excludeURL stringByReplacingCharactersInRange:match.range withString:@""];
                    }

                }
            }else{
                //全部替换为@""
                excludeURL = [excludeURL stringByReplacingCharactersInRange:match.range withString:@""];
            }
        }
        
        NSLog(@"%@", excludeURL);
    }
    
    return excludeURL;
}

-(NSString*)URLEncodedString{
    NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    return [self stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
}

-(NSString *)URLDecodeString{
    return [self stringByRemovingPercentEncoding];
}

- (NSString *)url_setValuesForKeysWithDictionary:(NSDictionary<NSString *,id> *)keyedValues{
    NSString *str = @"";
    for (id key in keyedValues.allKeys){
        id value = keyedValues[key];
        if (![value isEqual: [NSNull null]]){
            str = [str stringByAppendingFormat:@"%@=%@", key, keyedValues[key]];
        }
        if (![key isEqual:[keyedValues.allKeys lastObject]])
            str = [str stringByAppendingString:@"&"];
    }
    
    if ([self mj_keyValues].count > 0){
        return [self stringByAppendingFormat:@"&%@", str];
    }else{
        return [self stringByAppendingFormat:@"?%@", str];
    }
}

@end
